package v4.text;

public class TextJm {
	
	private TextJmConfig config;
	
	public TextJm(TextJmConfig config) {
		this.config = config;
	}
	
	final static char COLON = '=';  //支持冒号(:)逗号(,)分号(;)等号(=)等非Base64字符
	
	public String encrypt(String text, String k) {
		String pk = config.getRSA_PRIVATEKEY();
		int n = config.getTEXT_R_LEN();
		String r = config.rR(n);
		int x = config.rX();
		int y = config.rY();
		String hk = TotpKit.toHex(k);
		String totp = null;
		if(config.isUSE_TOTP()) {
			totp = TotpKit.createTotp(x+ "" +y, hk);
		}else {
			totp = x+ "" +y;
		}
		String mk = r + "." + totp + k;
		AesKit ak = new AesKit(config.getAES_KEYSIZE(), config.getAES_PADDING());
		String jm = ak.aes_encrypt(text, mk);
		try {
			String rxy = r + "" + (x-y) + "" + (x+y);
			String tk = RsaKit.rsa_encrypt(pk, rxy);
			String ret = tk + COLON + jm;
			return ret;
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage());
		}
	}
	
	static int findColon(String str) {
		int i = str.indexOf(COLON);
		if((i+1)<str.length()) {
			char c = str.charAt(i+1);
			while(COLON==c) {
				i++;
				c = str.charAt(i+1);
			}
		}
		return i;
	}
	
	public String decrypt(String etext, String k) {
		String pk = config.getRSA_PUBLICKEY();
		int n = config.getTEXT_R_LEN();
		int i = findColon(etext);
		String tk = etext.substring(0, i);
		String jm = etext.substring(i+1);
		String rxy = null;
		try {
			rxy = RsaKit.rsa_decrypt(pk, tk);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage());
		}
		String r = rxy.substring(0, n);
		String xy = rxy.substring(n, n+8);
		int q = Integer.parseInt(xy.substring(0, 4));
		int p = Integer.parseInt(xy.substring(4));
		int x = (p+q)/2;
		int y = (p-q)/2;
		String hk = TotpKit.toHex(k);
		String totp = null;
		if(config.isUSE_TOTP()) {
			totp = TotpKit.createTotp(x+ "" +y, hk);
		}else {
			totp = x+ "" +y;
		}
		String mk = r + "." + totp + k;
		AesKit ak = new AesKit(config.getAES_KEYSIZE(), config.getAES_PADDING());
		String ret = ak.aes_decrypt(jm, mk);
		return ret;
	}
	
	public String encryptAndCheck(String text, String k) {
		String etext = encrypt(text, k);
		String back = decrypt(etext, k);
		if(text.equals(back)) {
			return etext;
		}
		return null;
	}

}
